<template>
  <div class="panel-tab__content">
    <el-divider content-position="center">按钮设置</el-divider>
    <el-table :data="elementButtonList" size="small" max-height="240" border fit>
      <el-table-column label="序号" width="50px" type="index" />
      <el-table-column label="属性名" prop="name" min-width="100px" show-overflow-tooltip />
      <el-table-column label="属性值" prop="value" min-width="100px" show-overflow-tooltip />
      <el-table-column label="操作" width="90px">
        <template #default="{ row, $index }">
          <el-button size="small" text @click="openAttributesForm(row, $index)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="small" text type="danger" @click="removeAttributes(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="element-drawer__button_save">
      <el-button size="small" type="primary" :icon="Plus" @click="openAttributesForm(null, -1)">添加按钮</el-button>
    </div>

    <el-dialog v-model="buttonFormModelVisible" title="按钮配置" width="600px" append-to-body destroy-on-close>
      <el-form :model="buttonForm" label-width="80px" size="small" ref="attributeFormRef" @submit.native.prevent>
        <el-form-item label="属性名：" prop="label">
          <el-input v-model="buttonForm.label" clearable />
        </el-form-item>
        <el-form-item label="属性值：" prop="value">
          <el-input v-model="buttonForm.value" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="buttonFormModelVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveAttribute">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, inject, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { StrUtil } from "@/utils/StrUtil";

const props = defineProps({
  id: {
    type: String,
    required: true
  }
});

const modelerStore = inject('modelerStore');
const elementButtonList = ref([]);
const otherExtensionList = ref([]);
const buttonForm = ref({});
const editingPropertyIndex = ref(-1);
const buttonFormModelVisible = ref(false);
const attributeFormRef = ref(null);

let bpmnElement = null;
let bpmnElementProperties = [];
let bpmnElementButtonList = [];

// 监听ID变化，重置按钮列表
watch(() => props.id, (val) => {
  if (StrUtil.isNotBlank(val)) {
    resetAttributesList();
  }
}, { immediate: true });

// 重置按钮属性列表
const resetAttributesList = () => {
  bpmnElement = modelerStore.element;
  otherExtensionList.value = []; // 其他扩展配置
  bpmnElementProperties =
    bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
      if (ex.$type !== `flowable:Buttons`) {
        otherExtensionList.value.push(ex);
      }
      return ex.$type === `flowable:Buttons`;
    }) ?? [];

  // 保存所有的扩展属性字段
  bpmnElementButtonList = bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), []);
  // 复制显示
  elementButtonList.value = JSON.parse(JSON.stringify(bpmnElementButtonList ?? []));
};

// 打开属性表单
const openAttributesForm = (attr, index) => {
  editingPropertyIndex.value = index;
  buttonForm.value = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
  buttonFormModelVisible.value = true;
  
  // 使用nextTick而不是在其中调用回调
  if (attributeFormRef.value) attributeFormRef.value.clearValidate();
};

// 移除属性
const removeAttributes = (attr, index) => {
  ElMessageBox.confirm("确认移除该属性吗？", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消"
  })
    .then(() => {
      elementButtonList.value.splice(index, 1);
      bpmnElementButtonList.splice(index, 1);
      // 新建一个属性字段的保存列表
      const propertiesObject = modelerStore.moddle.create(`flowable:Properties`, {
        values: bpmnElementButtonList
      });
      updateElementExtensions(propertiesObject);
      resetAttributesList();
    })
    .catch(() => console.info("操作取消"));
};

// 保存属性
const saveAttribute = () => {
  const { name, value } = buttonForm.value;
  
  if (editingPropertyIndex.value !== -1) {
    modelerStore.modeling.updateModdleProperties(bpmnElement, bpmnElementButtonList[editingPropertyIndex.value], {
      name,
      value
    });
  } else {
    // 新建属性字段
    const newPropertyObject = modelerStore.moddle.create(`flowable:Button`, { name, value });
    // 新建一个属性字段的保存列表
    const propertiesObject = modelerStore.moddle.create(`flowable:Buttons`, {
      values: bpmnElementButtonList.concat([newPropertyObject])
    });
    updateElementExtensions(propertiesObject);
  }
  buttonFormModelVisible.value = false;
  resetAttributesList();
};

// 更新元素扩展属性
const updateElementExtensions = (properties) => {
  const extensions = modelerStore.moddle.create("bpmn:ExtensionElements", {
    values: otherExtensionList.value.concat([properties])
  });

  modelerStore.modeling.updateProperties(bpmnElement, {
    extensionElements: extensions
  });
};
</script>
